import React, { useState, useEffect } from 'react';
import { Link, useParams } from 'react-router-dom';
import { Book, ChevronRight, FileText, Folder, Search, Clock, ChevronDown, ChevronUp } from 'lucide-react';
import { loadAllNotes, getNoteCategories, loadNoteByIdFromAnyCategory } from '../utils/noteLoader';

const NotesList = () => {
  const { category } = useParams();
  const [notes, setNotes] = useState([]);
  const [categories, setCategories] = useState([]);
  const [filteredNotes, setFilteredNotes] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [loading, setLoading] = useState(true);
  const [expandedCategories, setExpandedCategories] = useState({});

  useEffect(() => {
    const loadData = async () => {
      try {
        const [loadedNotes, loadedCategories] = await Promise.all([
          loadAllNotes(),
          getNoteCategories()
        ]);
        setNotes(loadedNotes);
        setCategories(loadedCategories);
        
        // 默认收起所有分类
        const initialExpanded = {};
        loadedCategories.forEach(cat => {
          initialExpanded[cat.key] = false;
        });
        setExpandedCategories(initialExpanded);
        
        // 处理笔记过滤逻辑
        await filterNotesByCategory(loadedNotes, category);
      } catch (error) {
        console.error('加载笔记失败:', error);
      } finally {
        setLoading(false);
      }
    };
    
    loadData();
  }, [category]);

  const filterNotesByCategory = async (allNotes, categoryParam) => {
    if (!categoryParam) {
      setFilteredNotes(allNotes);
      return;
    }

    // 检查是否是具体的笔记ID
    const specificNote = await loadNoteByIdFromAnyCategory(categoryParam);
    if (specificNote) {
      setFilteredNotes([specificNote]);
      return;
    }

    // 按分类过滤
    const filtered = allNotes.filter(note => note.category === categoryParam);
    setFilteredNotes(filtered);
  };

  useEffect(() => {
    const applyFilters = async () => {
      await filterNotesByCategory(notes, category);
    };
    
    if (notes.length > 0) {
      applyFilters();
    }
  }, [notes, category]);

  useEffect(() => {
    if (searchTerm) {
      const filtered = filteredNotes.filter(note =>
        note.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        note.excerpt.toLowerCase().includes(searchTerm.toLowerCase())
      );
      setFilteredNotes(filtered);
    } else {
      filterNotesByCategory(notes, category);
    }
  }, [searchTerm]);

  const toggleCategoryExpansion = (categoryKey) => {
    setExpandedCategories(prev => ({
      ...prev,
      [categoryKey]: !prev[categoryKey]
    }));
  };

  const handleSubcategoryClick = async (subcategoryKey) => {
    const specificNote = await loadNoteByIdFromAnyCategory(subcategoryKey);
    if (specificNote) {
      setFilteredNotes([specificNote]);
    }
  };

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  const getCategoryInfo = (categoryKey) => {
    return categories.find(cat => cat.key === categoryKey) || { name: categoryKey, description: '' };
  };

  if (loading) {
    return (
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <div className="text-center">
          <div 
            className="animate-spin rounded-full h-12 w-12 mx-auto mb-4"
            style={{
              borderWidth: '2px',
              borderStyle: 'solid',
              borderColor: 'transparent',
              borderTopColor: 'var(--color-primary)'
            }}
          ></div>
          <p className="text-gray-600 dark:text-gray-300">加载笔记中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      {/* Header */}
      <div className="mb-12">
        <div className="flex items-center mb-6">
          <Book className="h-8 w-8 mr-3" style={{ color: 'var(--color-primary)' }} />
          <h1 className="text-4xl font-bold text-gray-900 dark:text-white">
            {category ? getCategoryInfo(category).name : '技术笔记'}
          </h1>
        </div>

        {/* Breadcrumb */}
        {category && (
          <nav className="flex items-center space-x-2 text-sm text-gray-500 dark:text-gray-400 mb-6">
            <Link to="/notes" className="transition-colors theme-color hover:opacity-80">
              笔记
            </Link>
            <ChevronRight className="h-4 w-4" />
            <span className="text-gray-900 dark:text-white font-medium">
              {getCategoryInfo(category).name}
            </span>
          </nav>
        )}

        <p className="text-lg text-gray-600 dark:text-gray-300 max-w-3xl">
          {category
            ? getCategoryInfo(category).description
            : '系统化的技术学习笔记，涵盖前端、后端、架构设计等多个领域'
          }
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
        {/* Sidebar - Categories */}
        <aside className="lg:col-span-1">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 sticky top-24">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center">
              <Folder className="h-5 w-5 mr-2" style={{ color: 'var(--color-primary)' }} />
              分类目录
            </h3>

            <nav className="space-y-1">
              <Link
                to="/notes"
                className={`block px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                  !category
                    ? 'text-white'
                    : 'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-white'
                }`}
                style={!category ? {
                  backgroundColor: 'var(--color-primary-light)',
                  color: 'var(--color-primary-dark)'
                } : {}}
              >
                全部笔记
              </Link>

              {categories.map(cat => (
                <div key={cat.key} className="space-y-1">
                  {/* 主分类 */}
                  <div className="flex items-center">
                    <Link
                      to={`/notes/${cat.key}`}
                      className={`flex-1 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                        category === cat.key
                          ? 'text-white'
                          : 'text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-white'
                      }`}
                      style={category === cat.key ? {
                        backgroundColor: 'var(--color-primary-light)',
                        color: 'var(--color-primary-dark)'
                      } : {}}
                    >
                      {cat.name}
                    </Link>

                    {/* 展开/收起按钮 */}
                    {cat.subcategories && cat.subcategories.length > 0 && (
                      <button
                        onClick={() => toggleCategoryExpansion(cat.key)}
                        className="ml-1 p-1 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
                      >
                        {expandedCategories[cat.key] ? (
                          <ChevronUp className="h-4 w-4 text-gray-400" />
                        ) : (
                          <ChevronDown className="h-4 w-4 text-gray-400" />
                        )}
                      </button>
                    )}
                  </div>

                  {/* 二级分类 */}
                  {cat.subcategories && expandedCategories[cat.key] && (
                    <div className="ml-4 space-y-1 border-l-2 border-gray-100 dark:border-gray-700 pl-3">
                      {cat.subcategories.map(subcat => (
                        <button
                          key={subcat.key}
                          onClick={() => handleSubcategoryClick(subcat.key)}
                          className={`w-full text-left px-3 py-1.5 rounded-lg text-xs transition-colors ${
                            category === subcat.key
                              ? 'font-medium'
                              : 'text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 hover:text-gray-700 dark:hover:text-gray-300'
                          }`}
                          style={category === subcat.key ? {
                            backgroundColor: 'var(--color-primary-light)',
                            color: 'var(--color-primary-dark)'
                          } : {}}
                        >
                          <div className="truncate">{subcat.name}</div>
                          {subcat.description && (
                            <div className="text-xs text-gray-400 dark:text-gray-500 mt-0.5 truncate">
                              {subcat.description}
                            </div>
                          )}
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </nav>
          </div>
        </aside>

        {/* Main Content */}
        <main className="lg:col-span-3">
          {/* Search */}
          <div className="mb-8">
            <div className="relative max-w-md">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-5 w-5" />
              <input
                type="text"
                placeholder="搜索笔记..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-10 pr-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:border-transparent"
                style={{
                  '--tw-ring-color': 'var(--color-primary)',
                  '--tw-ring-opacity': '0.5'
                }}
              />
            </div>
          </div>

          {/* Notes List */}
          <div className="space-y-6">
            {filteredNotes.map((note, index) => (
              <article
                key={note.id}
                className="bg-white dark:bg-gray-800 rounded-xl shadow-lg hover:shadow-xl card-animated overflow-hidden border border-gray-200 dark:border-gray-700 animate-fade-in-up opacity-0"
                style={{
                  '--hover-border-color': 'var(--color-primary)',
                  animationDelay: `${index * 0.1}s`,
                  animationFillMode: 'forwards'
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.borderColor = 'var(--color-primary)';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.borderColor = '';
                }}
              >
                <div className="p-6">
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex-1">
                      <div className="flex items-center mb-2">
                        <span
                          className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium mr-3"
                          style={{
                            backgroundColor: 'var(--color-primary-light)',
                            color: 'var(--color-primary-dark)'
                          }}
                        >
                          {getCategoryInfo(note.category).name}
                        </span>
                        <div className="flex items-center text-sm text-gray-500 dark:text-gray-400">
                          <Clock className="h-4 w-4 mr-1" />
                          {formatDate(note.date)}
                        </div>
                      </div>

                      <h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-3 transition-colors hover:theme-color">
                        <Link to={`/notes/${note.category}/${note.id}`}>
                          {note.title}
                        </Link>
                      </h2>

                      <p className="text-gray-600 dark:text-gray-300 mb-4 line-clamp-2">
                        {note.excerpt}
                      </p>

                      <div className="flex items-center justify-between">
                        <div className="flex items-center text-sm text-gray-500 dark:text-gray-400">
                          <FileText className="h-4 w-4 mr-1" />
                          {note.readTime}
                        </div>

                        <Link
                          to={`/notes/${note.category}/${note.id}`}
                          className="inline-flex items-center font-medium transition-all duration-300 group theme-color hover:opacity-80"
                        >
                          阅读笔记
                          <ChevronRight className="h-4 w-4 ml-1 group-hover:translate-x-2 transition-transform duration-300" />
                        </Link>
                      </div>
                    </div>
                  </div>
                </div>
              </article>
            ))}
          </div>

          {filteredNotes.length === 0 && (
            <div className="text-center py-12">
              <FileText className="h-16 w-16 text-gray-300 dark:text-gray-600 mx-auto mb-4" />
              <p className="text-gray-500 dark:text-gray-400 text-lg">
                {searchTerm ? '没有找到匹配的笔记' : '暂无笔记内容'}
              </p>
            </div>
          )}
        </main>
      </div>
    </div>
  );
};

export default NotesList;
